package com.shuaixin.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * Created by wby on 2015/5/17.
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    @RequestMapping(value = "/pic")
    public String toPerson8(HttpServletRequest request) throws Exception {

        MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;

        CommonsMultipartFile cfile = (CommonsMultipartFile) rm.getFile("pic");


        byte[] bfile = cfile.getBytes();
        String fileName = "";

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        fileName = format.format(new Date());

        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            fileName = fileName + random.nextInt(9);
        }

        String origFileName = cfile.getOriginalFilename();

        //XXX.jpg
        String suffix = origFileName.substring(origFileName.lastIndexOf("."));


        String path = request.getSession().getServletContext().getRealPath("");

        String avatarurl = path + "/assets/img/" + fileName + suffix;
        System.out.println(avatarurl);
        OutputStream out = new FileOutputStream(new File(path + "/assets/img/" + fileName + suffix));
        out.write(bfile);
        out.flush();
        out.close();

        return "/jsp/index.jsp";
    }

}
